<template>
  <div class="address-display">
    <el-tooltip
      :content="modelValue?.address"
      :disabled="!showTooltip"
      placement="top"
    >
      <el-text class="address-text" truncated @click="openMapDialog">
        {{ displayText }}
      </el-text>
    </el-tooltip>

    <el-dialog
      v-model="dialogVisible"
      title="位置详情"
      width="60%"
      height="80%"
      @closed="destroyMap"
      :append-to-body="true"
      teleported
    >
      <div class="map-container">
        <div v-if="loading" class="map-loading">地图加载中...</div>
        <div ref="mapContainer" class="map-wrapper"></div>

        <el-descriptions :column="1" border class="mt-4">
          <el-descriptions-item label="地址">{{
            modelValue.address
          }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{
            modelValue.lng
          }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{
            modelValue.lat
          }}</el-descriptions-item>
        </el-descriptions>

        <div class="dialog-footer mt-4">
          <el-button type="primary" @click="dialogVisible = false"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 高德地址展示组件
 * 经纬度格式: GCJ02
 * @param {Object} modelValue - 绑定的坐标对象
 * @param {number} modelValue.lng - 经度
 * @param {number} modelValue.lat - 纬度
 * @param {string} modelValue.address - 地址
 */
import { ref, computed, watch, nextTick } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { ElMessage } from 'element-plus';

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      address: '',
      lng: null,
      lat: null,
    }),
  },
});

const emit = defineEmits(['update:modelValue']);

// 高德地图配置
const securityJsCode = import.meta.env.VITE_APP_MAP_AMAP_SECRET; // 高德密钥
const mapKey = import.meta.env.VITE_APP_MAP_AMAP_KEY; // 高德密钥
window._AMapSecurityConfig = { securityJsCode };

// 响应式状态
const dialogVisible = ref(false);
const loading = ref(false);
const mapInstance = ref(null);
const mapContainer = ref(null);

// 显示控制
const displayText = computed(
  () => (props.modelValue && props.modelValue.address) || '暂无地址信息',
);

const showTooltip = computed(
  () =>
    props.modelValue &&
    props.modelValue.address &&
    props.modelValue.address.length > 20,
);

// 初始化地图
const initMap = async () => {
  try {
    loading.value = true;

    const AMap = await AMapLoader.load({
      key: mapKey,
      version: '2.0',
      plugins: ['AMap.Marker'],
    });

    mapInstance.value = new AMap.Map(mapContainer.value, {
      center: [props.modelValue.lng, props.modelValue.lat],
      zoom: 16,
      viewMode: '2D',
    });

    // 添加标记
    new AMap.Marker({
      position: [props.modelValue.lng, props.modelValue.lat],
      map: mapInstance.value,
    });
  } catch (error) {
    ElMessage.error('地图初始化失败');
  } finally {
    loading.value = false;
  }
};

// 打开弹窗
const openMapDialog = async () => {
  if (!validateCoordinates()) {
    return ElMessage.warning('无效的坐标信息');
  }

  dialogVisible.value = true;
  nextTick(async () => {
    if (!mapInstance.value) await initMap();
  });
};

// 坐标验证
const validateCoordinates = () => {
  const { lng, lat } = props.modelValue;
  return lng && lat && Math.abs(lng) <= 180 && Math.abs(lat) <= 90;
};

// 销毁地图
const destroyMap = () => {
  if (mapInstance.value) {
    mapInstance.value.destroy();
    mapInstance.value = null;
  }
};

// 坐标变化监听
watch(
  () => props.modelValue,
  (newVal) => {
    if (mapInstance.value && validateCoordinates()) {
      mapInstance.value.setCenter([newVal.lng, newVal.lat]);
    }
  },
);
</script>

<style scoped>
.address-display {
  cursor: pointer;
  display: inline-block;
  max-width: 400px;
}

.address-text {
  color: var(--el-color-primary);
  transition: color 0.3s;
  /* display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden; */
}

.address-text:hover {
  color: var(--el-color-primary-light-3);
  text-decoration: underline;
}

.map-container {
  position: relative;
  height: 60vh;
}

.map-wrapper {
  height: 400px;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.map-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.dialog-footer {
  text-align: right;
}
</style>
